package com.client;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.grpc.FutureProto;
import com.grpc.FutureServiceGrpc;
import com.grpc.HelloProto;
import com.grpc.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class FutureGrpcClient {

    public static void main(String[] args) {
        ManagedChannelBuilder<?> localhost = ManagedChannelBuilder.forAddress("localhost", 9000);
        ManagedChannel channel = localhost.usePlaintext().build();
        try {
//            获取存根，代理客户端发送请求。就像调用本地方法一样
            FutureServiceGrpc.FutureServiceFutureStub futureServiceFutureStub = FutureServiceGrpc.newFutureStub(channel);
            ListenableFuture<FutureProto.FutureResponse> future = futureServiceFutureStub.future(FutureProto.FutureRequest.newBuilder().setName("戴宗").build());

//            同步处理
//            FutureProto.FutureResponse futureResponse = future.get();
//            System.out.println(futureResponse.getResult());
//            System.out.println("后续的操作...");


//            异步操作处理
//            future.addListener(new Runnable() {
////                这种异步方式得不到响应结果
//                public void run() {
//                    System.out.println("异步的rpc响应来到了...");
//                }
//            }, Executors.newCachedThreadPool());
//
//            System.out.println("后续操作...");


            Futures.addCallback(future, new FutureCallback<FutureProto.FutureResponse>() {

                public void onSuccess(FutureProto.FutureResponse result) {
                    System.out.println("异步的rpc响应来到了... result = " + result.getResult());
                }

                public void onFailure(Throwable t) {

                }
            },Executors.newCachedThreadPool());

            System.out.println("后续操作...");

            channel.awaitTermination(15, TimeUnit.SECONDS);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            channel.shutdown();
        }
    }
}
